<template>
  <div class="p-2">
    <el-card shadow="never">
      <template #header>
        <el-form ref="queryFormRef" :inline="true">
          <el-form-item label="项目名称" prop="projectName">
            <el-select v-model="selectedName" placeholder="请选择项目" style="width: 240px" @change="onNameChange">
              <el-option v-for="(item, index) in names" :key="`select-project-${index}`" :label="item" :value="item" />
            </el-select>
          </el-form-item>

          <el-form-item label="楼栋" prop="towerNumber">
            <el-select v-model="selectedTowerNumber" placeholder="请选择楼栋" style="width: 240px" @change="handleQuery">
              <el-option v-for="(item, index) in filteredTowerNumbers" :key="`select-tower-${index}`" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">查 询</el-button>
          </el-form-item>
        </el-form>
      </template>

      <div v-if="flatRentalList && !!flatRentalList.length" class="flat-rental-container">
        <div class="flat-rental-legend">
          <div class="flat-rental-legend-empty">
            <span class="in_idle" style="width: 20px; height: 20px; display: inline-block" />
            <span>空置</span>
          </div>
          <div class="flat-rental-legend-leased">
            <span class="leased" style="width: 20px; height: 20px; display: inline-block" />
            <span>已出租</span>
          </div>
          <div class="flat-rental-legend-sold">
            <span class="have_been_sold" style="width: 20px; height: 20px; display: inline-block" />
            <span>已出售</span>
          </div>
        </div>

        <div class="flat-rental-view-list">
          <div v-for="(floor, floorNo) in flatRentalList" :key="`flat-rental-view-floor-${floorNo}`" class="flat-rental-view-floor">
            <div class="flat-rental-view-floor-title">
              第{{ parseInt(floor.floor || 0) < 10 ? '0' + parseInt(floor.floor || 0) : floor.floor }}层：
            </div>
            <div v-for="(room, roomNo) in floor.nests" :key="`flat-rental-view-room-${roomNo}`" class="flat-rental-view-room" :class="room.roomState">
              <p>{{ room.towerNumber }}# {{ room.roomNumber }}</p>
              <p>租赁人：{{ room.tenantName || '无' }}</p>
              <p>建筑面积：{{ room.floorArea || '0.00' }}㎡</p>
            </div>
          </div>
        </div>
      </div>

      <el-empty v-else />
    </el-card>
  </div>
</template>

<script setup name="FlatRentalVisualize" lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { listFlatbasicInfo } from '@/api/zichanguanli/flatbasicInfo';
import { listFlatrentalVisualize } from '@/api/zichanguanli/flatRentalVisualize';
import { FlatrentalVisualizeVO, FlatrentalVisualizeQuery } from '@/api/zichanguanli/flatRentalVisualize/types';

// 响应式变量
const selectedName = ref('');
const selectedTowerNumber = ref('');

// 提前生成 name -> towerNumber 映射
const nameToTowerNumbersMap = ref({});

// 提取所有唯一的 name
const names = ref([]);

// 根据 selectedName 获取对应的 towerNumber 列表
const filteredTowerNumbers = computed(() => {
  if (selectedName.value && nameToTowerNumbersMap.value[selectedName.value]) {
    return nameToTowerNumbersMap.value[selectedName.value];
  }
  return [];
});

const flatRentalList = ref<FlatrentalVisualizeVO[] | null>(null);

const getProjectInfo = async () => {
  const { rows } = await listFlatbasicInfo({
    pageSize: 1000,
    pageNum: 1
  });

  // 生成映射关系
  rows.forEach((item) => {
    if (!nameToTowerNumbersMap.value[item.name]) {
      nameToTowerNumbersMap.value[item.name] = new Set(); // 使用 Set 去重
    }
    nameToTowerNumbersMap.value[item.name].add(item.towerNumber); // 使用 add 来避免重复添加
  });

  // 将 Set 转为排序后的数组，并赋值给 names.value
  Object.keys(nameToTowerNumbersMap.value).forEach((name) => {
    // 将 Set 转换为数组，排序，并更新到映射
    nameToTowerNumbersMap.value[name] = Array.from(nameToTowerNumbersMap.value[name]).sort((a, b) => a - b);
  });

  names.value = Object.keys(nameToTowerNumbersMap.value);

  // 默认选择第一个 name 和对应的 towerNumber
  if (names.value.length > 0) {
    selectedName.value = names.value[0];
    selectedTowerNumber.value = nameToTowerNumbersMap.value[selectedName.value][0];
  }
};

const onNameChange = () => {
  // 当 name 变化时自动更新 selectedTowerNumber
  if (nameToTowerNumbersMap.value[selectedName.value]) {
    selectedTowerNumber.value = nameToTowerNumbersMap.value[selectedName.value][0];
  }
  getFlatrentalVisualizeList();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getFlatrentalVisualizeList();
};

const getFlatrentalVisualizeList = async () => {
  const { data } = await listFlatrentalVisualize({
    projectName: selectedName.value,
    towerNumber: selectedTowerNumber.value
  });

  flatRentalList.value = data;
};

const init = async () => {
  await getProjectInfo();
  await getFlatrentalVisualizeList();
};

onMounted(async () => {
  init();
});
</script>

<style scoped lang="scss">
p {
  margin: 0;
  padding: 0;
}

.flat-rental-legend {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 10px;

  & > div {
    display: flex;
    align-items: center;

    &:not(:last-child) {
      margin-right: 10px;
    }

    & > span:first-child {
      margin-right: 5px;
    }
  }
}

.flat-rental-container {
  overflow-x: auto;
  overflow-y: hidden;
}

.flat-rental-view-floor-title {
  font-weight: bold;
  margin-right: 20px;
  font-family: '苹方-简 Bold', '苹方-简 常规体', '苹方-简', sans-serif;
  font-weight: 700;
  font-style: normal;
  font-size: 18px;
}

.flat-rental-view-floor {
  display: flex;
  align-items: center;
  margin-bottom: 50px;
  width: 5000px;
}

.flat-rental-view-room {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20px 40px;
  border-radius: 10px;
  font-size: 14px;
  color: #333352;
  witdh: 200px;

  & > p:nth-child(2) {
    margin: 3px 0;
  }

  &:not(:last-child) {
    margin-right: 5px;
  }
}

.in_idle {
  background-color: #d7d7d7;
}

.leased {
  background-color: #70b603;
}

.have_been_sold {
  background-color: #73bcdd;
}
</style>
